<template>
    <div class="department-container">
      <a-card class="department-card" :bordered="false">
        <!-- 顶部标题和操作区 -->
        <div class="header-section">
          <h2 class="page-title">部门管理</h2>
          <div class="table-operations">
            <a-row :gutter="16" align="middle">
              <a-col :span="8">
                <a-input-search
                  v-model:value="search"
                  placeholder="搜索部门信息..."
                  @search="fetchDepartmentList"
                  enter-button
                  size="large"
                  class="search-input"
                />
              </a-col>
              <a-col :span="16" style="text-align: right">
                <a-button type="primary" size="large" @click="showAddModal" class="add-button">
                  <apartment-outlined />
                  新增部门
                </a-button>
              </a-col>
            </a-row>
          </div>
        </div>
  
        <!-- 部门表格 -->
        <a-table
          :columns="columns"
          :data-source="departmentList"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          class="custom-table"
          :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : '')"
        >
          <!-- 自定义列显示 -->
          <template v-slot:bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'departmentName'">
              <div class="department-name">
                <apartment-outlined class="dept-icon" />
                <span>{{ record.departmentName }}</span>
              </div>
            </template>
            <template v-if="column.dataIndex === 'employeeCount'">
              <a-tag color="blue">
                <team-outlined /> {{ getEmployeeCount(record.departmentId) }}
              </a-tag>
            </template>
            <template v-if="column.dataIndex === 'tripCount'">
              <a-tag color="green">
                <car-outlined /> {{ getTripCount(record.departmentId) }}
              </a-tag>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-space>
                <a-button type="link" @click="showEditModal(record)" class="edit-button">
                  <edit-outlined />
                  编辑
                </a-button>
                <a-popconfirm
                  title="确定要删除这个部门吗？"
                  @confirm="handleDelete(record.departmentId)"
                  ok-text="确定"
                  cancel-text="取消"
                >
                  <a-button type="link" danger class="delete-button">
                    <delete-outlined />
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
  
        <!-- 添加/编辑部门模态框 -->
        <a-modal
          :title="modalTitle"
          :open="modalVisible"
          @ok="handleModalOk"
          @cancel="handleModalCancel"
          class="department-modal"
          :maskClosable="false"
          :width="500"
        >
          <a-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="部门名称" name="departmentName">
              <a-input 
                v-model:value="formData.departmentName" 
                placeholder="请输入部门名称"
                class="custom-input"
              />
            </a-form-item>
          </a-form>
        </a-modal>
      </a-card>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { message } from 'ant-design-vue'
  import { 
    ApartmentOutlined, EditOutlined, DeleteOutlined,
    TeamOutlined, CarOutlined
  } from '@ant-design/icons-vue'
  import { list,add,del,update } from '@/api/department'
  import { getEmployeeByDepartment } from '@/api/driver'
  import { getVehicleByDepartment } from '@/api/vehicle'
  import {getDataList} from "@/api/data";
  // 表格列定义
  const columns = [
    {
      title: '部门名称',
      dataIndex: 'departmentName',
      key: 'departmentName',
    },
    {
        title:'人员数量',
        dataIndex:'employeeCount',
        key:'employeeCount'
        
    },
    {
        title:'出行次数',
        dataIndex:'tripCount',
        key:'tripCount'
    },
    {
      title: '操作',
      dataIndex:'action',
      key: 'action',
    },
  ]
  
  // 数据相关
  const loading = ref(false)
  const departmentList = ref([])
  const employeeList=ref([])
  const tripList=ref([])
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const search=ref('')
  // 模态框相关
  const modalVisible = ref(false)
  const modalTitle = ref('添加部门')
  const formRef = ref(null)
  const formData = ref({
    departmentName: '',
    description: '',
  })
  
  // 表单验证规则
  const rules = {
    departmentName: [
      { required: true, message: '请输入部门名称', trigger: 'blur' },
      { min: 2, max: 50, message: '部门名称长度应在 2-50 个字符之间', trigger: 'blur' },
    ]
  }
  // const fetchEmployeeList = async () => {
  //   try {
  //     const res = await getEmployeeByDepartment()
  //     if (res.code === 200) {
  //       employeeList.value = res.data
  //     }
  //   } catch (error) {
  //     message.error('获取部门人员数量失败')
  //   }
  // }
  // const fetchVehicleList = async () => {
  //   try {
  //     const res = await getVehicleByDepartment()
  //     if (res.code === 200) {
  //       vehicleList.value = res.data
  //     }
  //   } catch (error) {
  //     message.error('获取部门车辆数量失败')
  //   }
  // }
  const getData=async()=>{
    const res=await getDataList()
    if(res.code===200){
        tripList.value=res.data.tripCountByDepartment
        employeeList.value=res.data.peopleCountByDepartment
    }
  }
  const getEmployeeCount = (departmentId) => {
    const employee = employeeList.value.find(item => item.departmentId === departmentId)
    return employee ? employee.peopleCount : 0
  }
  const getTripCount = (departmentId) => {
    const trip = tripList.value.find(item => item.departmentId === departmentId)
    return trip ? trip.tripCount : 0
  }
  // 获取部门列表
  const fetchDepartmentList = async () => {
    loading.value = true
    try {
      const res = await list({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize,
        search: search.value
      })
      if (res.code === 200) {
        departmentList.value = res.data.records
        pagination.value.total = res.data.total
      }
    } catch (error) {
      message.error('获取部门列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 表格分页变化
  const handleTableChange = (pag) => {
    pagination.value.current = pag.current
    pagination.value.pageSize = pag.pageSize
    fetchDepartmentList()
  }
  
  // 显示添加模态框
  const showAddModal = () => {
    modalTitle.value = '添加部门'
    formData.value = {
      departmentName: '',
      description: '',
    }
    modalVisible.value = true
  }
  
  // 显示编辑模态框
  const showEditModal = (record) => {
    modalTitle.value = '编辑部门'
    formData.value = { ...record }
    modalVisible.value = true
  }
  
  // 处理模态框确认
  const handleModalOk = () => {
    formRef.value?.validate().then(async () => {
      try {
        //TODO: 调用后端 API 保存/更新部门信息
        const res=formData.value.departmentId ? await update(formData.value) : await add(formData.value)
        if(res.code===200){
            message.success(`${modalTitle.value}成功`)
            modalVisible.value = false
            fetchDepartmentList()
        }
      } catch (error) {
        message.error(`${modalTitle.value}失败`)
      }
    })
  }
  
  // 处理模态框取消
  const handleModalCancel = () => {
    modalVisible.value = false
    formRef.value?.resetFields()
  }
  
  // 处理删除部门
  const handleDelete = async (departmentId) => {
    try {
      // TODO: 调用后端 API 删除部门
       const res=await del(departmentId)
       if(res.code===200){
        message.success('删除成功')
        fetchDepartmentList()
       }
   
    } catch (error) {
      message.error('删除失败')
    }
  }
  
  // 搜索处理函数
  const onSearch = () => {
    pagination.value.current = 1 // 重置页码到第一页
    fetchDepartmentList()
  }
  
  // 页面加载时获取部门列表
  onMounted(() => {
    fetchDepartmentList()
    //fetchVehicleList()
    getData()
  })
  </script>
  
  <style scoped>
  .department-container {
    padding: 24px;
    background-color: #f0f2f5;
    min-height: 100vh;
  }
  
  .department-card {
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  }
  
  .header-section {
    margin-bottom: 24px;
  }
  
  .page-title {
    font-size: 24px;
    color: #1f1f1f;
    margin-bottom: 24px;
    font-weight: 500;
  }
  
  .search-input {
    width: 100%;
    :deep(.ant-input) {
      border-radius: 4px;
    }
  }
  
  .add-button {
    border-radius: 4px;
    height: 40px;
    font-weight: 500;
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
  }
  
  .custom-table {
    :deep(.ant-table-thead > tr > th) {
      background: #fafafa;
      font-weight: 500;
    }
    
    :deep(.table-striped) {
      background-color: #fafafa;
    }
  }
  
  .department-name {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .dept-icon {
      color: #1890ff;
      background: #e6f7ff;
      padding: 4px;
      border-radius: 50%;
    }
  }
  
  .edit-button {
    color: #1890ff;
  }
  
  .delete-button {
    color: #ff4d4f;
  }
  
  .department-modal {
    :deep(.ant-modal-header) {
      border-bottom: 1px solid #f0f0f0;
      padding: 16px 24px;
    }
    
    :deep(.ant-modal-footer) {
      border-top: 1px solid #f0f0f0;
      padding: 16px 24px;
    }
  }
  
  .custom-input,
  .custom-textarea {
    width: 100%;
    :deep(.ant-input),
    :deep(.ant-input-textarea) {
      border-radius: 4px;
    }
  }
  
  /* 添加动画效果 */
  .add-button,
  .edit-button,
  .delete-button {
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-1px);
    }
  }
  
  /* 响应式调整 */
  @media (max-width: 768px) {
    .department-container {
      padding: 12px;
    }
    
    .page-title {
      font-size: 20px;
    }
    
    .header-section {
      margin-bottom: 16px;
    }
    
    .search-input,
    .add-button {
      margin-bottom: 12px;
    }
  }
  </style>
